package zsc.ruanc.practicaltraining.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 从字符串中提取url进行删除
 *
 * 当文章删除时，从文章中提取图片、文件等资源进行删除
 */
@Component
public class DeleteUtils {

    @Value("${cbs.imagesPath.file}")
    private String resPath;

    @Async
    public void delete(String text) {


        String htmlStr = text;
        Set<String> pics = new HashSet<>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }

        for (String pic : pics) {

            String targetPath = pic.replace("/res/", resPath);
            File file = new File(targetPath);
            file.delete();
        }

    }

}
